/**
 * 
 */
package org.jenkon;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Class with method to serialize and deserialize.
 * 
 * @author Jens Konopka
 * 
 */
public class Serializer {

	/**
	 * Serialize the given object to a byte array.
	 * 
	 * @param object the object to serialize
	 * @return an array of bytes representing the object in a portable fashion
	 */
	public byte[] serialize(final Object object) {
		final ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			final ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			oos.flush();
		} catch (final IOException ex) {
			throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
		}
		return baos.toByteArray();
	}

	/**
	 * Deserialize the byte array into an object.
	 * 
	 * @param bytes a serialized object
	 * @return the result of deserializing the bytes
	 */
	public Object deserialize(final byte[] bytes) {
		try {
			final ByteArrayInputStream bain = new ByteArrayInputStream(bytes);
			final ObjectInputStream objectInputStream = new ObjectInputStream(bain);
			return objectInputStream.readObject();
		} catch (final IOException ex) {
			throw new IllegalArgumentException("Failed to deserialize object", ex);
		} catch (final ClassNotFoundException ex) {
			throw new IllegalStateException("Failed to deserialize object type", ex);
		}
	}

}
